package com.kcloud.ms.gateway.openid.config;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.openid.OpenIDAttribute;

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //    Log log = LogFactory.getLog(SecurityConfig.class);

    /**
     * 定义安全策略
     */
    @Override
    // @formatter:off
    protected void configure(HttpSecurity http) throws Exception {
        OpenIDAttribute email = new OpenIDAttribute("email", "https://schema.openid.net/contact/email");
        email.setRequired(true);
        http.csrf().disable().authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and().openidLogin()
//                .loginPage("/index").permitAll()
                .loginProcessingUrl("/j_spring_openid_security_check")
//                .loginPage("http://openid.org.cn/").permitAll()

//                .loginPage("https://sso.ztjs.cn/accounts/openid").permitAll()
                .authenticationUserDetailsService(new CustomUserDetailsService())
                .attributeExchange(".*sso.ztjs.cn.*")
                    .attribute("email")
                    .type("http://openid.net/schema/contact/internet/email")
                    .required(true)
                .and()
                    .attribute("fullname")
                    .type("http://openid.net/schema/namePerson/friendly")
                    .required(true)
                .and()
                    .attribute("id")
                    .type("http://sso.ztjs.cn/schema/user/id")
                    .required(true)
                .and().and()
                .attributeExchange(".*openid.org.cn.*")
                    .attribute("email")
                    .type("https://schema.openid.net/contact/email")
                    .required(true)
                .and()
                    .attribute("fullname")
                    .type("https://schema.openid.net/namePerson")
                    .required(true)
                .and()
                    .attribute("id")
                    .type("https://schema.openid.net/user/id")
                    .required(true)
                ;
    }
    // @formatter:on
}
